(function() {
    'use strict';

    /**
     * @ngdoc function
     * @name webApp.controller:ProductCtrl
     * @description
     * # ProductCtrl
     * Controller of the webApp
     */
    angular.module('webApp')
        .controller('ProductCtrl', ProductCtrl);

    ProductCtrl.$inject = ['$scope', 'dataService', '$location', '$state', 'helper', '$timeout'];

    function ProductCtrl($scope, dataService, $location, $state, helper, $timeout) {

        /**
         *listAction产品列表初始化
         *getProductList产品列表查询
         *addproductcat选中产品线返回的方法
         *setpostage_id选中运费模板返回方法
         *addAction添加（编辑）产品初始化方法
         *productDelete根据产品id删除一条产品数据
         *productAdd根据是否有产品id来判断是新增还是编辑修改产品
         *
         */

        $scope.listAction = function() {
            $scope.productsTotal = 0;
            $scope.pageSize = 10;
            $scope.getProductList(1);
        }
        $scope.getProductList = function(pageNo) {
            var query = {
                page_no: pageNo ? pageNo : "1",
                page_size: $scope.pageSize
            };
            if ($scope.pid) {
                query.query = {
                    "pid": $scope.pid
                };
            }
            if ($scope.name) {
                query.query = {
                    "name": $scope.name
                };
            }
            dataService.supllerProductGet(query).then(function(list) {
                if (list) {
                    console.log(list);
                    $scope.productslist = list.shop;
                    $scope.productsTotal = list.total_count;
                }
            });
        }

        $scope.shelv = function(pid) {
            dataService.supllerProductUnshowUpdate(pid).then(function(r) {
                if (r.Msg) {
                    helper.myAlert("erro:" + r.Msg);
                } else {
                    helper.myAlert("success", null, null, function() {
                        $scope.listAction();
                    })
                }
            });
        }

        $scope.theshelves = function(pid) {
            dataService.supllerProductShowUpdate(pid).then(function(r) {
                if (r.Msg) {
                    helper.myAlert("erro:" + r.Msg);
                } else {
                    helper.myAlert("success", null, null, function() {
                        $scope.listAction();
                    })
                }
            });
        }

        $scope.addproductcat = function(productcat) {
            console.log("ddd", productcat);
            $scope.product.productcat_id = productcat.id;
        }

        $scope.setpostage_id = function(fareTemplate) {
            $scope.product.postage_id = fareTemplate.fare_id;
        }

        $scope.addAction = function() {
            $scope.product = {};
            var pid = $location.search().pid;
            if (pid) {
                $scope.GetItemOne(pid);
            } else {
                $scope.product = {};
                $scope.skuNew = [{ "pid": random(), "name": "颜色", "values": [{ "id": random(), "value": "红色", "mark": "" }, { "id": random(), "value": "", "mark": "" }] }];
                // $scope.product.category_id = 3312321312;
                $scope.productcat_id = 111111111111111111;
                $scope.product.cost_price = 0;
                $scope.product.dealer_cost_price = 0;
                $scope.product.discount_id = 11111111;
                $scope.product.have_guarantee = false;
                $scope.product.have_invoice = true;
                $scope.product.image_url = "https://g-search1.alicdn.com/img/bao/uploaded/i4/imgextra/i2/188620136570582931/TB28ruZgVXXXXbuXXXXXXXXXXXX_!!12368862-0-saturn_solar.jpg_230x230.jpg";
                $scope.product.name = "耐克旅游鞋";
                $scope.product.outer_id = 33333333333;
                // $scope.product.items_count = 0;
                $scope.product.postage_fast = 0;
                $scope.product.postage_id = 111111;
                // $scope.product.orders_count = 0;
                $scope.product.quantity = 0;
                $scope.product.alarm_number = 0;
                $scope.product.retail_price_high = 0;
                $scope.product.retail_price_low = 0;
                // $scope.product.standard_price = 0;
                // // $scope.product.standard_retail_price = 0;
                // $scope.product.skus = [];
                // $scope.product.skus[0]={}
                // $scope.product.skus[0].name = "耐克鞋广州产";
                // $scope.product.skus[0].outer_id = 212333;
                // $scope.product.skus[0].image_url = "http://yy.dhfeng.com/static/uploads/2016-11-30/deac5fd8-f0d3-4fe3-a3e4-2f1ce09a0841.png";
                // $scope.product.skus[0].pur_standard_price = 0;

                // $scope.product.skus[0].retail_standard_price = 0;
                // // $scope.product.skus[0].standard_price = 0;
                // $scope.product.skus[0].quantity = 0;
            }
            $scope.$watch("skuNew", function(nVal, oVal) {
                $scope.addNewSkuData();
                console.log("dddddddddddddddddddddddddddddd", $scope.skuNew);
                console.log(" $scope.product ", $scope.product);
            }, true);
        }

        $scope.isSelected = function(value, name) {
            if (value) {
                return true;
            }
        };

        $scope.GetItemOne = function(pid) {
            dataService.supllerProductOne(pid).then(function(one) {
                if (one) {
                    $scope.product = clone(one);
                    $scope.updateSkuType();
                    $scope.clproduct = clone(one);
                    $scope.isid = one.pid;
                } else {
                    helper.myAlert("No data found", null, null, function() {
                        $state.go("product.list");
                    });
                }
            });
        }

        //分解sku 组装淘宝格式 显示
        $scope.updateSkuType = function() {
            if ($scope.product) {
                var fgeoneDate = splitAry();
                if (fgeoneDate) {
                    var arr = oneConTwo(fgeoneDate); //将一维数组 转换有父子关系的二维数组
                    var aryData = unique5(arr); //去除重复值；
                    if (aryData) {
                        var newata = [];
                        _.map(aryData, function(dd, kk) {
                            newata.push({ pid: dd.pid, name: dd.name, values: [] });
                            var len = dd.values;
                            for (var j = 0; j < len.length; j++) {
                                if (len[j]) {
                                    newata[kk].values.push(len[j]);
                                }
                                if (len.length == j + 1) {
                                    newata[kk].values.push({ id: 0, value: "", mark: "" });
                                }
                            }

                        });
                        $scope.skuNew = newata;
                    }
                }
                // console.log("arr", arr);
            }
        }

        $scope.addNskuName = function(name, key, $event) {
            if (name) {
                _.map($scope.skuNew, function(d, k) {
                    if (d.name == name && key !== k) {
                        helper.myAlert(name + "该属性已经存在");
                        $scope.skuNew[key].name = "";
                    }
                });
            }
        }
        $scope.addNsku = function(name, val, pid, key) {
                $timeout(function() {
                    var data = "1";
                    _.map($scope.skuNew, function(d, k) {
                        if (val) {
                            if (d.name == name) {
                                _.map(d.values, function(isvd, kk) {
                                    if (isvd.value == val && (key !== kk)) {
                                        helper.myAlert(name + "[" + val + "]" + "该类型已经存在");
                                        d.values[key].value = "";
                                        data = "2";
                                    }
                                })
                            }
                        }
                    });
                    return data;
                }).then(function(data) {
                    // console.log("ddddd", val);
                    if (data == "1" && val) {
                        $scope.addValues(name, pid, key);
                    }
                });
            }
            //增加 values 数据
        $scope.addValues = function(name, pid, key) {
                // 选中时 增加新的 数据
                _.map($scope.skuNew, function(d, k) {
                    if (key >= 0) {
                        if (!d.values[key + 1]) {
                            if ((d.name == name) && (pid == d.pid)) {
                                d.values.push({ id: random(), value: "", mark: "" });
                            }
                        }
                    } else {
                        if ((d.name == name) && (pid == d.pid)) {
                            d.values.push({ id: random(), value: "", mark: "" });
                        }
                    }
                });
            }
            //增加属性
        $scope.addNewSkuVaue = function(name, va, $event, key, pid) {
            var checkbox = $event.target;
            if (checkbox.checked) {
                // 选中时 增加新的 数据
                $scope.addValues(name, pid);
            } else {
                //取消选中 删除 取消的值
                _.map($scope.skuNew, function(d, k) {
                    if (d.name == name) {
                        _.map(d.values, function(isvd, kk) {
                            if (key == kk) {
                                d.values.splice(kk, 1);
                            }
                        });
                    }
                });
            }
        }

        //添加api 值 自动监控
        $scope.addNewSkuData = function() {
            // console.log("$scope.skuNew", $scope.skuNew);
            if (!$scope.product.pid) {
                $scope.product.skus = [];
            }
            zuhgdata();
            zuhgdata(1);
        }

        //整理数据
        function zuhgdata(type) {
            var seate = [];
            _.map($scope.skuNew, function(d, k) {
                if (d) {
                    if (type) {
                        seate[k] = [];
                    }
                    _.map(d.values, function(isd, isk) {
                        if (isd.value) {
                            if (type) {
                                // seate[k] = [];
                                seate[k].push({ id: isd.id, value: isd.value, tname: d.name, pid: d.pid });
                            }
                        } else {
                            delete isd[isk];
                        }
                    });
                } else {
                    $scope.skuNew.splice(k, 1);
                }
            });
            // console.log("seate=====================",seate);
            // seate = _.compact(seate);
            _.map(seate, function(is, kk) {
                if (is.length <= 0) {
                    seate.splice(kk, 1);
                }
            });
            if (seate.length > 0) {
                $scope.SortingData = cartesian(seate);
                if ($scope.clproduct) {
                    $scope.product.skus = clone($scope.clproduct.skus);
                }
                if ($scope.SortingData) {
                    var skuAry = [];
                    _.map($scope.SortingData, function(sd, sk) {
                        var dd = '';
                        console.log("sdsdsdsdsd", sd);
                        _.map(sd, function(ssd, ssk) {
                            dd += ssd.pid + ':' + Number(ssd.id) + ':' + ssd.tname + ":" + ssd.value + ';';
                        });
                        $scope.product.skus.push(skuDefault(dd));
                    });
                    // console.log(" $scope.product.skus", $scope.product.skus);
                    var skuNwewData = unique5sku($scope.product.skus);
                    if (skuNwewData) {
                        if ($scope.isid && type) {
                            if (skuNwewData.length === $scope.clproduct.skus.length) {
                                $scope.product.skus = skuNwewData;
                            } else {
                                $scope.product.skus = $scope.clproduct.skus;
                            }
                            $scope.isid = '';
                        } else {
                            $scope.product.skus = skuNwewData;
                        }

                    }
                    // console.log(" $scope.product.skus", $scope.product.skus);
                }
            }
        }

        //去除二维数组中 重复 的一维数组
        function unique5sku(arrays) {
            for (var i = 0, l = arrays.length; i < l; i++) {
                // console.log(l);
                for (var j = i + 1; j < l; j++) {
                    //判断 第一个和第二个数组 内容是否相同 ，id相同 就代表数据相同
                    if (arrays[i].properties === arrays[j].properties) {
                        arrays[j] = [];
                        j = ++i;
                    }
                }
            }
            var newSkuData = [];
            _.map(arrays, function(dd, kk) {
                if (dd.properties) {
                    newSkuData.push(dd);
                }
            });
            // console.log("newSkuDatanewSkuDatanewSkuData",newSkuData);
            return newSkuData;
        }

        //排列组合
        function cartesian(arg) {
            // console.log("arg", arg);
            var r = [],
                max = arg.length - 1;

            function helper(arr, i) {
                if (!arg[i]) {
                    return false;
                }
                for (var j = 0, l = arg[i].length; j < l; j++) {
                    var a = arr.slice(0); // clone arr
                    a.push(arg[i][j]);
                    // console.log("aaaaaaa", a);
                    if (i == max)
                        r.push(a);
                    else
                        helper(a, i + 1);
                }
            }
            helper([], 0);
            return r;
        }

        //拆分，切割数组，组成需要是一维数组 
        function splitAry() {
            var skusDateAry = [];
            _.map($scope.product.skus, function(da, k) {
                skusDateAry.push({ data: da.properties });
            });
            var fgeoneDate = [];
            _.map(skusDateAry, function(dss, kk) {
                var strs = dss.data.split(";");
                strs = strs.filter(function(n) {
                    return n
                });
                if (strs) {
                    _.map(strs, function(dd, kk) {
                        var svbtrs = dd.split(":");
                        if (svbtrs[0] && svbtrs[2] && svbtrs[1] && svbtrs[3]) {
                            fgeoneDate.push({ pid: Number(svbtrs[0]), name: svbtrs[2], id: Number(svbtrs[1]), value: svbtrs[3] })
                        }
                    });
                }
            });
            // console.log("装的数据",fgeoneDate);
            return fgeoneDate;
        }

        //将多个带有父子关系的一维数组，转换为二维数组
        function oneConTwo(fgeoneDate) {
            var map = {};
            var arr = [];
            for (var i = 0; i < fgeoneDate.length; i++) {
                var di = fgeoneDate[i];
                var n = di.pid;
                if (!map[n]) {
                    //先判断 pid是否有只 有值 先给父级赋值
                    map[n] = di.name;
                    arr.push({ pid: n, name: di.name, values: [{ id: di.id, value: di.value }] });
                } else {
                    for (var j = 0; j < arr.length; j++) {
                        var aj = arr[j];
                        if (aj.pid == n) {
                            //pid相等的时候，在给子类赋值
                            arr[j].values.push({ id: di.id, value: di.value });
                            break;
                        }
                    }
                }
            }
            // console.log("arrarrarrarrarrarrarrarr=", arr);
            return arr;
        }

        //去除二维数组中 重复 的一维数组
        function unique5(arrays) {
            _.map(arrays, function(arra, k) {
                var array = arra.values;
                for (var i = 0, l = array.length; i < l; i++) {
                    for (var j = i + 1; j < l; j++) {
                        //判断 第一个和第二个数组 内容是否相同 ，id相同 就代表数据相同
                        if (array[i].id === array[j].id) {
                            delete arra.values[i];
                            j = ++i;
                        }
                    }
                }
            });
            // console.log("arraysarraysarraysarrays=", arrays);
            return arrays;
        }

        $scope.productDelete = function(pid) {
            dataService.supllerProductDelete(pid).then(function(r) {
                if (r.Msg) {
                    helper.myAlert("erro:" + r.Msg);
                } else {
                    helper.myAlert("success", null, null, function() {
                        $scope.listAction();
                    });

                }
            });
        }
        $scope.productAdd = function() {
            // console.log("分销产品", $scope.product);
            zuzhuangItem($scope.product);
        }

        $scope.productItemAdd = function(product) {
            dataService.supllerProductAdd(product).then(function(r) {
                if (r.Msg) {
                    helper.myAlert("erro:" + r.Msg);
                } else {
                    helper.myAlert("success", null, null, function() {
                        $state.go("product.list");
                    });
                }
            });
        }

        $scope.productItemUpdate = function(product) {
            dataService.supllerProductUpdate(product).then(function(r) {
                if (r.Msg) {
                    helper.myAlert("erro:" + r.Msg);
                } else {
                    helper.myAlert("success", null, null, function() {
                        $state.go("product.list");
                    });
                }
            });
        }

        $scope.addSku = function() {
            if (!$scope.product.skus) {
                $scope.product.skus = [];
            };
            $scope.product.skus.push(skuDefault());
        }

        //获取增加的规格数据
        $scope.addNewSku = function(sku) {
            if ($scope.skuNew) {
                // $scope.skuNew = [];
                $scope.skuNew.push({ pid: random(), name: "", values: [{ id: random(), value: "", }] });
            } else {
                $scope.skuNew = [{ pid: random(), name: "", values: [{ id: random(), value: "", }] }];
            }
        }

        //添加商品
        function zuzhuangItem(itemData) {
            var skusData = clone(itemData);
            var sdata = skusData.skus;
            async.mapSeries(sdata, function(dss, cb) {
                var data = dss.properties;
                var strs = data.split(";");
                strs = strs.filter(function(n) {
                    return n
                });
                if (strs) {
                    var sevt = '';
                    async.mapSeries(strs, function(dd, cb1) {
                        var svbtrs = dd.split(":");
                        dataService.itemSkuTypeGet({ query: { name: svbtrs[2] } }).then(function(r) {
                            if (r.sku_types[0]) {
                                svbtrs[0] = r.sku_types[0].id;
                                jyvalue();
                            } else {
                                dataService.itemSkuTypeAdd({ name: svbtrs[2] }).then(function(isr) {
                                    svbtrs[0] = isr.id;
                                    jyvalue();
                                });
                            }

                            function jyvalue() {
                                dataService.itemSkuValueGet({ query: { name: svbtrs[3], pid: svbtrs[0] } }).then(function(vr) {
                                    if (vr.sku_values[0]) {
                                        svbtrs[1] = vr.sku_values[0].id;
                                        sevt += svbtrs[0] + ":" + svbtrs[1] + ":" + svbtrs[2] + ":" + svbtrs[3] + ";";
                                        cb1(null);
                                    } else {
                                        dataService.itemSkuValueAdd({ pid: svbtrs[0], name: svbtrs[3] }).then(function(svbr) {
                                            svbtrs[1] = svbr.id;
                                            sevt += svbtrs[0] + ":" + svbtrs[1] + ":" + svbtrs[2] + ":" + svbtrs[3] + ";";
                                            cb1(null);
                                        });
                                    }
                                });
                            }
                        });
                    }, function(e, d) {
                        dss.properties = sevt;
                        cb(null)
                    })
                } else {
                    cb(null);
                }
            }, function(e, d) {
                console.log("skusData", skusData);
                // return;
                if (skusData.pid) {
                    $scope.productItemUpdate(skusData);
                } else {
                    $scope.productItemAdd(skusData);
                }
            })
        }

        function skuDefault(properties) {
            var outer_id = "S00" + random(11111, 99999);
            return {
                outer_id: outer_id,
                name: outer_id + "的名字",
                properties: properties,
                image_url: "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png",
                pur_standard_price: 0,
                retail_standard_price: 0,
                retail_price_high: 0,
                retail_price_low: 0,
                quantity: 1, //数量
            };
        }
    }
})();
